<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import {
  getAlertSceneListApi,
  deleteAlertSceneApi,
  updateAlertSceneStatusApi,
  AlertSceneModel
} from "@/api/alerts/alertScene";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useI18n } from "vue-i18n";
// 引入新增和编辑组件
import AddAlertScene from './component/add.vue';
import EditAlertScene from './component/edit.vue';
// 引入关联操作组件
import BindSceneToPeople from './component/bind-scene-to-people.vue';
import BindSceneToDevice from './component/bind-scene-to-device.vue';
import BindSceneToGroup from './component/bind-scene-to-group.vue';
import { useLogic } from "@/views/system/user/logic/logic";
import { DeviceModel } from "@/api/products/device";

defineOptions({
  name: "alert-scene"
});

const i18n = useI18n();
const { t } = i18n;
const pageSizeOps = ref(pageSizeOptions);

const {deptTreeList,getDeptTree}  = useLogic()
onMounted(async () => {
  await getDeptTree()

})

const searchDefault = {
  name: "",
  timeRange: [],
  dept_id: undefined,
  pageSize: 10,
  page: 1,
}
// 搜索参数
const searchParams = ref(Object.assign({},searchDefault));

// 搜索字段配置
const searchFields = ref([
  {
    prop: "name",
    name: t("alerts.scenePage.search.name"),
    type: "input",
    placeholder: "",
  },
  { prop: 'deptId', name: t("products.devicePage.deptId"), type: 'cascader', cascaderOptions: deptTreeList, ops: { valueField: 'id', labelField: 'name', emitPath: false, checkStrictly: true } },
  { prop: 'timeRange', name: t("buttons.timeRange"), type: 'datetimeRange', clearable: true, isHidden: false, },
]);

// 表格数据
const tableData = ref<AlertSceneModel[]>([]);
const total = ref(0);
const loading = ref(false);
const selectedRows = ref<AlertSceneModel[]>([]);

// 对话框控制变量
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentScene = ref<AlertSceneModel | null>(null);
// 关联操作对话框控制变量
const bindPeopleDialogVisible = ref(false);
const bindDeviceDialogVisible = ref(false);
const bindGroupDialogVisible = ref(false);
const currentBindScene = ref<AlertSceneModel | any>({});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = { ...searchParams.value };
    const response = await getAlertSceneListApi(params);
    if (response.code === 0) {
      tableData.value = response.data?.list || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.msg || t('alerts.scenePage.getFailed'));
    }
  } catch (error) {
    total.value = 0;
    tableData.value = [];
    ElMessage.error(t('alerts.scenePage.getFailed'));
    console.error("Failed to load alert scene list:", error);
  } finally {
    loading.value = false;
  }
};

// 初始加载
onMounted(() => {
  loadData();
});

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  loadData();
};
const handlePaginationPageChange = (page: number) => {
  searchParams.value.page = page;
  loadData();
};

// 搜索处理
const handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
};

const handleSearch = async (e: any) => {
  searchParams.value.page = 1;
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await loadData();
};

const handleReset = (e: any) => {
  searchParams.value  =Object.assign({},searchDefault)
};

// 刷新列表
const refreshList = () => {
  loadData();
};

// 打开新增对话框
const handleAdd = () => {
  addDialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row: AlertSceneModel) => {
  currentScene.value = { ...row };
  editDialogVisible.value = true;
};

// 打开关联人员对话框
const handleBindPeople = (row: AlertSceneModel) => {
  currentBindScene.value = row;
  bindPeopleDialogVisible.value = true;
};

// 打开关联设备对话框
const handleBindDevice = (row: AlertSceneModel) => {
  currentBindScene.value = row;
  bindDeviceDialogVisible.value = true;
};

// 打开关联分组对话框
const handleBindGroup = (row: AlertSceneModel) => {
  currentBindScene.value = row;
  bindGroupDialogVisible.value = true;
};

// 删除操作
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      t('alerts.scenePage.deleteConfirm'),
      t('buttons.confirm'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const response = await deleteAlertSceneApi(id);
    if (response.code === 0) {
      ElMessage.success(t('alerts.scenePage.deleteSuccess'));
      refreshList();
    } else {
      ElMessage.error(response.msg || t('alerts.scenePage.deleteFailed'));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error(t('alerts.scenePage.deleteFailed'));
    }
  }
};

// 批量删除
const handleSelectionChange = (rows: AlertSceneModel[]) => {
  selectedRows.value = rows;
};

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t('alerts.scenePage.selectRecordFirst'));
    return;
  }

  try {
    await ElMessageBox.confirm(
      t('alerts.scenePage.batchDeleteConfirm', { count: selectedRows.value.length }),
      t('buttons.confirm'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const ids = selectedRows.value.map(row => row.id);
    // 循环删除，因为接口只支持单个删除
    let allSuccess = true;
    for (const id of ids) {
      const response = await deleteAlertSceneApi(id);
      if (response.code !== 0) {
        allSuccess = false;
        break;
      }
    }

    if (allSuccess) {
      ElMessage.success(t('alerts.scenePage.batchDeleteSuccess'));
      await loadData();
      selectedRows.value = [];
    } else {
      ElMessage.error(t('alerts.scenePage.batchDeleteFailed'));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error(t('alerts.scenePage.batchDeleteFailed'));
    }
  }
};

// 格式化绑定范围显示
const formatBindTo = (bindTo: number) => {
  return bindTo === 0 ? t('alerts.scenePage.bindTo.singleDevice') : t('alerts.scenePage.bindTo.group');
};

// 格式化通知类型
const formatNoticeType = (noticeType: string) => {
  if (!noticeType) return '';
  const types = noticeType.split(',');
  const typeMap: Record<string, string> = {
    'email': 'Email',
    'sms': 'SMS'
  };
  return types.map(t => typeMap[t] || t).join(' & ');
};

// 格式化判断符号
const formatJudgeMark = (judgeMark: string) => {
  const marks: Record<string, string> = {
    '<': '&lt;',
    '=': '=',
    '<=': '&lt;=',
    '>': '&gt;',
    '>=': '&gt;='
  };
  return marks[judgeMark] || judgeMark;
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="search-area">
        <Searchbox
          :fields="searchFields"
          :initialValues="searchParams"
          :maxVisibleFields="1"
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>
    <div class="button-area">
      <el-button type="primary" icon="Plus" @click="handleAdd">
        {{ t('buttons.add') }}
      </el-button>
      <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        {{ t('buttons.batchDelete') }}
      </el-button>
    </div>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
<!--      <el-table-column prop="id" :label="'ID'" width="80" />-->
      <el-table-column prop="name" :label="t('alerts.scenePage.table.name')" min-width="100" />
      <el-table-column prop="englishName" :label="t('alerts.scenePage.table.englishName')" min-width="100" />
      <el-table-column prop="type" :label="t('alerts.scenePage.table.type')" width="100" />
      <el-table-column prop="level" :label="t('alerts.scenePage.table.level')" width="60" />
      <el-table-column prop="frequency" :label="t('alerts.scenePage.table.frequency')" width="120" />
      <el-table-column prop="noticeType" :label="t('alerts.scenePage.table.noticeType')" width="120">
        <template #default="{ row }">
          {{ formatNoticeType(row.noticeType) }}
        </template>
      </el-table-column>
      <el-table-column prop="deptName" :label="t('alerts.scenePage.table.dept')" width="100" />
      <el-table-column prop="bindTo" :label="t('alerts.scenePage.table.bindTo')" width="120">
        <template #default="{ row }">
          {{ formatBindTo(row.bindTo) }}
        </template>
      </el-table-column>
      <el-table-column prop="judgeMark" :label="t('alerts.scenePage.table.judgeMark')" width="100">
        <template #default="{ row }">
          <span v-html="formatJudgeMark(row.judgeMark)"></span>
        </template>
      </el-table-column>
<!--      <el-table-column prop="remark" :label="t('alerts.scenePage.table.remark')" min-width="150" />-->
      <el-table-column prop="createdAt" :label="t('alerts.scenePage.table.createdAt')" width="180" />
      <el-table-column :label="t('alerts.scenePage.table.operation')" width="250">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(row)"
          >
            {{ t('buttons.edit') }}
          </el-button>
          <el-button
            size="small"
            @click="handleBindPeople(row)"
          >
            {{ t('alerts.sceneOperatePage.bindPeople') }}
          </el-button>
          <template v-if="row.bindTo === 0">
            <el-button
              size="small"
              @click="handleBindDevice(row)"
            >
              {{ t('alerts.sceneOperatePage.bindDevice') }}
            </el-button>
          </template>
          <template v-if="row.bindTo === 1">
            <el-button
              size="small"
              @click="handleBindGroup(row)"
            >
              {{ t('alerts.sceneOperatePage.bindGroup') }}
            </el-button>
          </template>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row.id)"
          >
            {{ t('buttons.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="searchParams.page"
      v-model:page-size="searchParams.pageSize"
      :page-sizes="pageSizeOps"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePaginationSizeChange"
      @current-change="handlePaginationPageChange"
    />

    <!-- 新增对话框 -->
    <AddAlertScene
      v-model:visible="addDialogVisible"
      @success="refreshList"
    />

    <!-- 编辑对话框 -->
    <EditAlertScene
      v-model:visible="editDialogVisible"
      :scene="currentScene"
      @success="refreshList"
    />

    <!-- 关联人员对话框 -->
    <BindSceneToPeople
      v-model:visible="bindPeopleDialogVisible"
      :scene-id="currentBindScene.id"
      :dept-id="currentBindScene.deptId"
      @success="refreshList"
    />

    <!-- 关联设备对话框 -->
    <BindSceneToDevice
      v-model:visible="bindDeviceDialogVisible"
      :scene-id="currentBindScene.id"
      :dept-id="currentBindScene.deptId"
      @success="refreshList"
    />

    <!-- 关联分组对话框 -->
    <BindSceneToGroup
      v-model:visible="bindGroupDialogVisible"
      :scene-id="currentBindScene.id"
      :dept-id="currentBindScene.deptId"
      @success="refreshList"
    />
  </el-card>
</template>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.button-area {
  margin: 16px 0;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.search-area {
  margin-bottom: 16px;
}
</style>

